package tech.xiaoniu.aspect

import android.annotation.SuppressLint
import android.util.Log
import org.aspectj.lang.JoinPoint
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.annotation.Before
import org.aspectj.lang.annotation.Pointcut
import org.aspectj.lang.reflect.MethodSignature

/**
 * 切面类
 */
@Aspect
class MyAspect {
    // 切点
    @Pointcut(POINTCUT)
    fun debugLog() {
    }

    @Pointcut("execution(void androidx.appcompat.app.AppCompatActivity.onCreate(..))")
    fun OnCreate() {
    }

    @Pointcut("execution(void android.webkit.WebViewClient.onPageFinished(..))")
    fun wbShouldOverrideUrlLoading() {
    }


    @Before("debugLog()")
    fun beforeDebugLog(joinPoint: JoinPoint) {
        try {
            val className = joinPoint.getThis().javaClass.simpleName
            val methodName = joinPoint.signature.name
            val signature = joinPoint.signature as MethodSignature
            val method = signature.method
            val arsgs = joinPoint.args
            val annotation = method.getAnnotation(DebugLog::class.java)
            if (annotation == null) {
                Log.e(TAG, "before: annotation == null")
            } else {
                Log.i(TAG, "Method invoked: $className.$methodName")
                Log.i(TAG,  "${arsgs.size}")
                for (sd in arsgs){
                    Log.i(TAG,  "${sd.toString()}")
                }

            }
        } catch (e: Throwable) {
            Log.e(TAG, "beforeDebugLog: failed on error: ", e)
        }
    }

    @Before("OnCreate()")
    fun beforeOnCreate(joinPoint: JoinPoint){
        Log.i(TAG, "my  aj  success！！！")
    }

    @Before("wbShouldOverrideUrlLoading()")
    fun beWbShouldOverrideUrlLoading(joinPoint: JoinPoint){
        Log.i(TAG, "wbShouldOverrideUrlLoading！！！")

        var args = joinPoint.getArgs();

        for (ob in args){

            Log.w(TAG,ob.toString())
        }
    }

    companion object {
        private val TAG = MyAspect::class.java.simpleName
        const val POINTCUT = "execution(@tech.xiaoniu.aspect.DebugLog * *(..))"
    }
}